package com.xnyzc.lhy.mis.service.impl.punishment;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.javafx.binding.StringFormatter;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.common.util.TokenUtil;
import com.xnyzc.lhy.mis.entity.account.OaDAccountAdjustment;
import com.xnyzc.lhy.mis.entity.account.OaDAccountAdjustmentInfo;
import com.xnyzc.lhy.mis.entity.dictionaries.OaSysDict;
import com.xnyzc.lhy.mis.entity.order.OaCOrderPersonal;
import com.xnyzc.lhy.mis.entity.param.punishment.DriverPenaltyTmpResult;
import com.xnyzc.lhy.mis.entity.param.punishment.OaDUserPenaltyParam;
import com.xnyzc.lhy.mis.entity.param.punishment.OaDUserPenaltyQueryParam;
import com.xnyzc.lhy.mis.entity.punishment.OaDUserPenalty;
import com.xnyzc.lhy.mis.entity.punishment.OaDUserPenaltyDetail;
import com.xnyzc.lhy.mis.entity.punishment.OaDUserPenaltyInfo;
import com.xnyzc.lhy.mis.mapper.dictionaries.OaSysDictMapper;
import com.xnyzc.lhy.mis.mapper.order.OaCOrderPersonalMapper;
import com.xnyzc.lhy.mis.mapper.punishment.OaDUserPenaltyDetailMapper;
import com.xnyzc.lhy.mis.mapper.punishment.OaDUserPenaltyMapper;
import com.xnyzc.lhy.mis.service.punishment.IOaDUserPenaltyService;
import com.xnyzc.lhy.order.entity.order.OaCOrderApprovalOfficial;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.eac.EACException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 司机处罚表  服务实现类
 * </p>
 *
 * @author cuixiaojian
 * @since 2019-10-27
 */
@Service
@Slf4j
public class OaDUserPenaltyServiceImpl extends ServiceImpl<OaDUserPenaltyMapper, OaDUserPenalty> implements IOaDUserPenaltyService {
    @Autowired
    OaDUserPenaltyMapper oaDUserPenaltyMapper;
    @Autowired
    OaDUserPenaltyDetailMapper oaDUserPenaltyDetailMapper;
    @Autowired
    OaSysDictMapper oaSysDictMapper;
    @Autowired
    private OaCOrderPersonalMapper oacOrderPersonalMapper;

    /**
     * 查询司机是否处罚字典
     */
    @Override
    public Rv slectIsPenalty() {
        Long sysUserId = TokenUtil.getTokenUserId();
        List<String> dataScope = TokenUtil.getRoleDataScope();
        if (CheckUtil.objIsEmpty(dataScope) || CheckUtil.objIsEmpty(sysUserId)) {
            throw PangException.create(EErrorCode.missingArg);
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(OaSysDict.TYPE, OaDUserPenalty.IS_PENALTY);
        List<OaSysDict> list = oaSysDictMapper.selectList(queryWrapper);
        return Rv.wrap(list);
    }

    /**
     * 添加司机处罚信息
     */
    @Override
    @Transactional
    public Rv insertoaDUserPenalty(List<OaDUserPenaltyParam> oaDUserPenaltyParamList) {

        OaDUserPenalty oaDUserPenalty = null;
        OaDUserPenaltyDetail oaDUserPenaltyDetail = null;
        QueryWrapper<OaDUserPenalty> oaDUserPenaltyQueryWrapper = null;
        Date date = new Date();
        if (oaDUserPenaltyParamList != null && oaDUserPenaltyParamList.size() > 0) {
            //校验司机与订单是否匹配
            for (OaDUserPenaltyParam oaDUserPenaltyParam : oaDUserPenaltyParamList) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq(OaCOrderPersonal.DRIVER_ID, oaDUserPenaltyParam.getDriverId());
                queryWrapper.eq(OaCOrderPersonal.ORDER_NO, oaDUserPenaltyParam.getOrderNumber());
                List<OaCOrderPersonal> oaCOrderPersonalList = oacOrderPersonalMapper.selectList(queryWrapper);
                if (oaCOrderPersonalList == null
                        || oaCOrderPersonalList.size() <= 0) {
                    String errorMsg = String.format(
                            "司机id：%s，订单号：%s，的订单不存在",
                            oaDUserPenaltyParam.getDriverId(),
                            oaDUserPenaltyParam.getOrderNumber());
                    log.info(errorMsg);
                    throw new PangException(EErrorCode.penaltyOrderNone.setDesc(errorMsg));
                }
            }

            for (OaDUserPenaltyParam oaDUserPenaltyParam : oaDUserPenaltyParamList) {
                //首先根据司机id 查询表中是否存在 此司机处罚信息
                oaDUserPenaltyQueryWrapper = new QueryWrapper<>();
                oaDUserPenaltyQueryWrapper.eq(OaDUserPenalty.DRIVER_ID, oaDUserPenaltyParam.getDriverId());
                oaDUserPenalty = oaDUserPenaltyMapper.selectOne(oaDUserPenaltyQueryWrapper);
                if (oaDUserPenalty == null) {
                    oaDUserPenalty = new OaDUserPenalty();
                    Long oaDUserPenaltyId = IDUtil.nextId();
                    oaDUserPenalty.setPenaltyId(oaDUserPenaltyId);
                    oaDUserPenalty.setDriverId(oaDUserPenaltyParam.getDriverId());
                    oaDUserPenalty.setCumulativeNumberViolations(1);
                    oaDUserPenalty.setPunishmentType(oaDUserPenaltyParam.getPunishmentType());
                    oaDUserPenalty.setIsPenalty(1);
                    oaDUserPenalty.setCreateTime(date);
                    oaDUserPenaltyMapper.insert(oaDUserPenalty);
                } else {
                    oaDUserPenalty.setCumulativeNumberViolations(oaDUserPenalty.getCumulativeNumberViolations() + 1);
                    oaDUserPenalty.setIsPenalty(1);
                    oaDUserPenalty.setPunishmentType(oaDUserPenaltyParam.getPunishmentType());
                    oaDUserPenaltyMapper.updateById(oaDUserPenalty);
                }

                //查询是否存在"司机+订单+处罚类型"的记录，如果没有进行处罚，增加同类型违规数量，如果已经处罚，报错返回，回滚
                QueryWrapper<OaDUserPenaltyDetail> oaDUserPenaltyDetailWrapper = new QueryWrapper<OaDUserPenaltyDetail>();
                oaDUserPenaltyDetailWrapper.eq(OaDUserPenaltyDetail.DRIVER_ID, oaDUserPenaltyParam.getDriverId());
                oaDUserPenaltyDetailWrapper.eq(OaDUserPenaltyDetail.ORDER_NUMBER, oaDUserPenaltyParam.getOrderNumber());
                oaDUserPenaltyDetailWrapper.eq(OaDUserPenaltyDetail.PUNISHMENT_TYPE, oaDUserPenaltyParam.getPunishmentType());
                oaDUserPenaltyDetail = oaDUserPenaltyDetailMapper.selectOne(oaDUserPenaltyDetailWrapper);

                if (oaDUserPenaltyDetail == null) {
                    oaDUserPenaltyDetail = new OaDUserPenaltyDetail();
                    Long oaDUserPenaltyDetailId = IDUtil.nextId();
                    oaDUserPenaltyDetail.setDetailId(oaDUserPenaltyDetailId);
                    oaDUserPenaltyDetail.setDriverId(oaDUserPenaltyParam.getDriverId());
                    oaDUserPenaltyDetail.setPenaltyId(oaDUserPenalty.getPenaltyId());
                    oaDUserPenaltyDetail.setWorkOrderNumber(oaDUserPenaltyParam.getWorkOrderNumber());
                    oaDUserPenaltyDetail.setOrderNumber(oaDUserPenaltyParam.getOrderNumber());
                    oaDUserPenaltyDetail.setPunishmentType(oaDUserPenaltyParam.getPunishmentType());
                    oaDUserPenaltyDetail.setPenaltyAmount(1);
                    oaDUserPenaltyDetail.setCreateUser(TokenUtil.getTokenUserId());
                    oaDUserPenaltyDetail.setCreateTime(date);
                    oaDUserPenaltyDetailMapper.insert(oaDUserPenaltyDetail);
                } else {
                    String errorMsg = String.format(
                            "司机id：%s，订单号：%s，违规类型：%s，已经执行处罚！",
                            oaDUserPenaltyDetail.getDriverId(),
                            oaDUserPenaltyDetail.getOrderNumber(),
                            oaDUserPenaltyDetail.getPunishmentType());
                    log.info(errorMsg);
                    throw new PangException(EErrorCode.penaltyDetailDone.setDesc(errorMsg));
                }
            }
            return Rv.wrap(EErrorCode.success);
        }
        return Rv.wrap(EErrorCode.noData);
    }

    /**
     * 查询司机处罚列表
     */
    @Override
    public Rv queryDriverPenaltyList(OaDUserPenaltyQueryParam oaDUserPenaltyQueryParam) {
        IPage iPage = new Page();
        iPage.setSize(oaDUserPenaltyQueryParam.getPageSize());
        iPage.setCurrent(oaDUserPenaltyQueryParam.getCurrent());
        List<OaDUserPenaltyInfo> oaDUserPenaltyInfos = oaDUserPenaltyMapper.queryDriverPenaltyList(iPage,
                oaDUserPenaltyQueryParam.getDriverName(),
                oaDUserPenaltyQueryParam.getDriverPhone(),
                oaDUserPenaltyQueryParam.getAdCode(),
                oaDUserPenaltyQueryParam.getIsPenalty());
        iPage.setRecords(oaDUserPenaltyInfos);
        return Rv.wrap(EErrorCode.success, iPage);
    }

    /**
     * 获取司机处罚模板和司机违规模板id
     *
     * @return
     */
    @Override
    public DriverPenaltyTmpResult getDriverPenaltyTmpId() {
        DriverPenaltyTmpResult driverPenaltyTmpResult = baseMapper.queryDriverPenaltyTmp();
        return driverPenaltyTmpResult;
    }
}
